package com.ai.aicontact.busi.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.aicontact.busi.entity.ExecInstruction;
import com.ai.aicontact.busi.service.ExecInstService;
import com.ai.aicontact.common.vo.PageFilter;
import com.ai.aicontact.core.dao.BaseDaoI; 

@Service
public class ExecInstServiceImpl implements ExecInstService {

	@Autowired
	private BaseDaoI<ExecInstruction> execInstructionDao;

	public List<ExecInstruction> queryExecInstuction(String keyWord, ExecInstruction execInstruction, PageFilter pf) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		StringBuilder hql = new StringBuilder("from ExecInstruction ");
		hql.append(whereHql(keyWord, execInstruction, params));
		hql.append(orderHql(pf)); 
		List<ExecInstruction> list = execInstructionDao.find(hql.toString(), params, pf.getPageNumber(), pf.getPageSize());
		return list;

	}

	private String whereHql(String keyWord, ExecInstruction execInstruction, Map<String, Object> params) {
		StringBuilder hql = new StringBuilder(" where 1=1 ");
		if (StringUtils.isNotEmpty(keyWord)) {
			hql.append(
					"AND (actName like :actName or actMainName like :actMainName  or actTitle like :actTitle  or actDiscription like :actDiscription  or sendContent like :sendContent or creator like :creator )");
			params.put("actName", "%" + keyWord + "%");
			params.put("actMainName", "%" + keyWord + "%");
			params.put("actTitle", "%" + keyWord + "%");
			params.put("actDiscription", "%" + keyWord + "%");
			params.put("sendContent", "%" + keyWord + "%");
			params.put("creator", "%" + keyWord + "%");
		}
		if (execInstruction.getCriticalPointId() != null && execInstruction.getCriticalPointId() > 0) {
			hql.append(" AND criticalPointId = :criticalPointId");
			params.put("criticalPointId", execInstruction.getCriticalPointId());
		}
		if (execInstruction.getActStatus() != null && execInstruction.getActStatus() > 0) {
			hql.append(" AND actStatus = :actStatus");
			params.put("actStatus", execInstruction.getActStatus());
		}

		return hql.toString();
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by " + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	public Long countExecInstuction(String keyWord, ExecInstruction execInstruction) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		StringBuilder hql = new StringBuilder("select count(*) from ExecInstruction ");
		hql.append(whereHql(keyWord, execInstruction, params));
		Long total = execInstructionDao.count(hql.toString(), params);
		return total;

	}
}
